import React, { PureComponent, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Card, Form, Button, Badge, Divider, Modal, Row, Col, Input, Select, DatePicker } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import NewCutIn from '../../components/UpLoadForm/NewCutIn';
import EditCutIn from '../../components/UpLoadForm/EditCutIn';
import styles from './MatterLib.less';
import car from '../../assets/car.png';

const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['待审核', '已审核', '已驳回'];
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const CreateForm = Form.create()(NewCutIn);
const EidtMatForm = Form.create()(EditCutIn);
const { Option } = Select;

@connect(({ cutinlib, dev, loading }) => ({
    cutinlib,
    dev,
    loading: loading.models.cutinlib,
}))
@Form.create()
export default class CutInLib extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            modalVisible: false,
            selectedRows: [],
            matDetail: {},
            editVisible: false,
        };
        this.method = 'pub';
    }
    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'cutinlib/fetch',
            payload: {
                page: 1,
                pageSize: 10,
            },
        });

        dispatch({
            type: 'dev/fetchCityCodes',
        });

        dispatch({
            type: 'cutinlib/fetchMatType',
        });

    }
    onFresh = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'cutinlib/fetch',
            payload: {},
        });
    };

    getFormValue = () => {
        const { form } = this.props;
        let postvalue = {};
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const { entries } = Object;
            for (const [key, value] of entries(fieldsValue)) {
                if (value !== null && value !== undefined) {
                    postvalue[key] = value;
                }
            }

            if (postvalue.date && postvalue.date.length > 0) {
                const startSubDate = postvalue.date[0].format('YYYY-MM-DD');
                const endSubDate = postvalue.date[1].format('YYYY-MM-DD');
                postvalue = {
                    ...postvalue,
                    startSubDate,
                    endSubDate,
                };
                delete postvalue.date;
            }
            console.log('postvalue', postvalue)
        });

        return postvalue;
    };

    handleSearch = e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const postvalue = this.getFormValue();
        //console.log('values', postvalue);

        dispatch({
            type: 'cutinlib/fetch',
            payload: postvalue,
        });
    };

    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const postvalue = this.getFormValue();

        const params = {
            page: pagination.current,
            pageSize: pagination.pageSize,
            ...postvalue,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }
        dispatch({
            type: 'rule/fetch',
            payload: params,
        });
    };
    delMatter = () => {
        Modal.confirm({
            title: '确认删除',
            content: '确认要删掉这些素材么，删除后不可恢复?',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                const { dispatch } = this.props;
                const { selectedRows } = this.state;
                if (selectedRows.length === 0) return;
                //console.log('slectROws', selectedRows);
                dispatch({
                    type: 'rule/remove',
                    payload: {
                        matId: selectedRows,
                    },
                    callback: () => {
                        this.setState({
                            selectedRows: [],
                        });
                    },
                });
            },
            onCancel() {
                //console.log('Cancel');
            },
        });
    };

    handleSelectRows = rows => {
        this.setState({
            selectedRows: rows,
        });
    };

    handleModalVisible = flag => {
        this.setState({
            modalVisible: !!flag,
        });
    };

    edit = record => {
        const { imeId } = record
        console.log('record', imeId)
        this.props.dispatch({
            type: 'cutinlib/fetchCutDetail',
            payload: {
                imeId
            }
        });
        this.setState({ editVisible: true, matDetail: record });
    };

    handleEditModalVisible = flag => {
        this.setState({
            editVisible: !!flag,
        });
    };




    render() {
        const { cutinlib, loading, dev: { cityCodes } } = this.props;
        const { matTypeCodes, tempType, matExampleUrl, imeDetail } = cutinlib

        //console.log('rule VideoCode', rule.VideoCode);
        const { selectedRows, modalVisible, editVisible, matDetail } = this.state;
        const columns = [
            {
                title: '创建时间',
                dataIndex: 'createTime',

            },
            {
                title: '实例名称',
                dataIndex: 'imeName',
            },
            {
                title: '实例类型',
                dataIndex: 'matType',
            },
            {
                title: '缩略图',
                dataIndex: 'imeUrl',
                render: thumbnail => (
                    <img src={thumbnail || car} className={styles.Appimg} alt="icon" size="small" />
                ),
            },
            {
                title: '播放时长',
                dataIndex: 'icPlayTimeLen',
            },
            {
                title: '更新时间',
                dataIndex: 'updateTime',
            },
            {
                title: '操作',
                render: (text, record, index) => (
                    <Fragment>
                        {/* 
                        <Button onClick={this.edit}>
                            详情
                        </Button>
                        <Divider type="vertical" /> */}
                        <a
                            onClick={() => this.edit(record)}
                        >
                            详情
                        </a>
                    </Fragment>
                ),
            },
        ];

        const parentMethods = {
            handleModalVisible: this.handleModalVisible,
            handleEditModalVisible: this.handleEditModalVisible,
            onFresh: this.onFresh,
        };
        const { getFieldDecorator } = this.props.form;
        return (
            <PageHeaderLayout>
                <Card bordered={false} title="模板列表">
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            <Form onSubmit={this.handleSearch}>
                                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                                    <Col md={5} sm={24}>
                                        <FormItem>
                                            {getFieldDecorator('date')(
                                                <RangePicker
                                                    format="YYYY-MM-DD"
                                                    placeholder={['开始时间', '结束时间']}
                                                    // onChange={onChange}
                                                    // onOk={onOk}
                                                    style={{ width: '100%' }}
                                                />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={6} md={4} sm={24}>
                                        <FormItem>
                                            {getFieldDecorator('matExampleName', {
                                                rules: [{ required: false, message: '请输入素材名称!' }],
                                            })(<Input placeholder="实例名称" />)}
                                        </FormItem>
                                    </Col>
                                    <Col span={6} md={3} sm={24}>
                                        <FormItem>
                                            {getFieldDecorator('matType')(
                                                <Select allowClear="true" placeholder="插播素材类型" style={{ width: '100%' }}>
                                                    {matTypeCodes.map((item, index) => (
                                                        <Option value={item.code}>{item.name}</Option>
                                                    ))}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={6} md={3} sm={24}>
                                        <span className={styles.submitButtons}>
                                            <Button
                                                type="primary"
                                                htmlType="submit"
                                                style={{ marginRight: 20 }}
                                                onClick={this.handleSearch}
                                            >
                                                查询
                      </Button>
                                            <Button
                                                style={{ marginRight: 20 }}
                                                icon="plus"
                                                type="primary"
                                                onClick={() => this.handleModalVisible(true)}
                                            >
                                                添加
                      </Button>
                                            <Button type="primary" style={{ marginRight: 20 }} >
                                                删除
                      </Button>
                                            <Button type="primary" onClick={this.onFresh}>
                                                刷新
                      </Button>
                                        </span>
                                    </Col>
                                </Row>
                            </Form>
                        </div>
                        <StandardTable
                            rowKey="matId"
                            selectedRows={selectedRows}
                            loading={loading}
                            data={cutinlib}
                            columns={columns}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
                <CreateForm
                    {...parentMethods}
                    modalVisible={modalVisible}
                    cityCodes={cityCodes}
                    matType={matTypeCodes}
                    tempType={tempType}
                    matExampleUrl={matExampleUrl}
                    dispatch={this.props.dispatch}
                />

                <EidtMatForm
                    {...parentMethods}
                    cityCodes={cityCodes}
                    matType={matTypeCodes}
                    tempType={tempType}
                    modalVisible={editVisible}
                    dispatch={this.props.dispatch}

                    imeDetail={imeDetail}
                />
                )
            </PageHeaderLayout>
        );
    }
}
